<template>
  <div class="chat">
    <div class="chat-title">
      <span class="iconfont icon-back" @click="backToSelectChat"></span>
      <span>{{ chatuser.username }} 聊天中...</span>
      <span class="iconfont icon-gengduo"></span>
    </div>
    <!-- 聊天列表 -->
    <div class="wrapper">
      <div class="content">
        <div class="chat-list">
          <div
            class="chat-item"
            :class="{ self: item.from.username === loginuser.username }"
            v-for="(item, index) in chatList"
            :key="'chatList' + index"
          >
            <template v-if="item.from.username === loginuser.username">
              <div class="item-content">
                <span v-if="item.type === 0">{{ item.content }}</span>
                <span v-else @click="previewImgFun(item.content)">
                  <i class="iconfont icon-tupian"></i>
                  {{ item.content | pathToFileName }}
                </span>
                <div class="sanjiao"></div>
                <div class="time-content">
                  {{ new Date(item.time).toLocaleTimeString() }}
                </div>
              </div>
              <img :src="item.from.avatarurl" alt="" />
            </template>
            <template v-else>
              <img :src="item.from.avatarurl" alt="" />
              <div class="item-content">
                <span v-if="item.type === 0">{{ item.content }}</span>
                <span v-else @click="previewImgFun(item.content)">
                  <i class="iconfont icon-tupian"></i>
                  {{ item.content | pathToFileName }}
                </span>
                <div class="sanjiao"></div>
                <div class="time-content">
                  {{ new Date(item.time).toLocaleTimeString() }}
                </div>
              </div>
            </template>
          </div>
        </div>
      </div>
    </div>

    <div class="input-com">
      <label
        for="upload"
        class="iconfont icon-jiahao
"
      ></label>
      <input
        type="text"
        @keydown.enter="sendMsgFun"
        v-model="inputContent"
        placeholder="typing..."
      />

      <label
        @click="sendMsgFun"
        class="iconfont icon-fasong
"
      ></label>
      <input
        id="upload"
        type="file"
        name="somefile"
        @change="upLoadFile($event)"
        accept="image/gif,image/jpg,image/jpeg,image/bmp,image/png"
      />
      <!-- accept=".docx,.doc,.pdf" -->
    </div>
    <preview-img v-if="showPreviewImg" :imgUrl="previewImgUrl" />
  </div>
</template>

<script>
import socket from '../socket'
import BScroll from 'better-scroll'
import PreviewImg from './PreviewImg'
export default {
  components: {
    PreviewImg,
  },
  props: ['chatuser', 'loginuser', 'unreadlist'],
  data() {
    return {
      inputContent: '',
      chatList: [],
      bscroll: null,
      addArr: [],
      showPreviewImg: false,
      previewImgUrl: '',
    }
  },
  filters: {
    pathToFileName(val) {
      let arr = val.split('\\')
      return arr[arr.length - 1]
    },
  },

  mounted() {
    this.bscroll = new BScroll('.wrapper', {
      // 0,1 不实时监测位置，2，监测，但不监测惯性滚动，3，监测并监测惯性滚动
      probeType: 3,
      click: true,
    })

    // 触发 将未读消息事件 置为已读
    socket.emit('readUnRead', {
      username: this.loginuser.username,
    })

    // 将当前聊天对象的未读信息整理成聊天记录
    this.chatList.push(...this.processChatList(this.unreadlist))

    // 获取50条历史消息
    socket.emit('getReadedMsgToServe', {
      loginuser: this.loginuser,
      chatuser: this.chatuser,
    })
    socket.on('getReadedMsgToWeb', (data) => {
      this.chatList.push(...this.processChatList(data))
      this.scrollChatList(0)
    })

    // // 监听在线用户直接发来的消息
    socket.on('directAcceptMsg', (data) => {
      console.log('接收在线用户直接发来的消息')
      this.chatList.push(data)
      // 窗口滚动
      this.scrollChatList(500)
    })
  },

  methods: {
    // 处理聊天记录成所需对象
    processChatList(listData) {
      let list = []
      // 按时间倒序
      listData.sort((a, b) => {
        return a.time - b.time
      })
      listData.forEach((item) => {
        if (item.fromuser === this.chatuser.username) {
          const obj = {
            content: item.content,
            from: {
              username: this.chatuser.username,
              avatarurl: this.chatuser.avatarurl,
            },
            to: {
              username: this.loginuser.username,
              avatarurl: this.loginuser.avatarurl,
            },
            time: item.time,
            type: item.type,
          }

          list.push(obj)
        } else {
          const obj = {
            content: item.content,
            to: {
              username: this.chatuser.username,
              avatarurl: this.chatuser.avatarurl,
            },
            from: {
              username: this.loginuser.username,
              avatarurl: this.loginuser.avatarurl,
            },
            time: item.time,
            type: item.type,
          }
          list.push(obj)
        }
      })

      return list
    },

    // 发送消息
    // 默认 type=0 普通消息，
    // type=1 发送了文件消息
    sendMsgFun($event, type = 0, fileInfo = null) {
      const msg = {
        from: this.loginuser,
        to: this.chatuser,
        content: '',
        time: new Date().getTime(),
        type: type,
      }

      if (type !== 0) {
        msg.content = fileInfo.path
      } else {
        if (this.inputContent.trim() === '') return
        msg.content = this.inputContent
      }

      this.chatList.push(msg)

      socket.emit('sendMsg', msg)

      this.inputContent = ''

      // 窗口滚动
      this.scrollChatList(500)
    },
    // 上传文件
    upLoadFile(event) {
      this.addArr = []
      var file = event.target.files
      for (var i = 0; i < file.length; i++) {
        //    上传类型判断
        var imgName = file[i].name
        var idx = imgName.lastIndexOf('.')
        if (idx != -1) {
          var ext = imgName.substr(idx + 1).toUpperCase()
          ext = ext.toLowerCase()
          // if (ext != 'pdf' && ext != 'doc' && ext != 'docx') {
          // } else {
          this.addArr.push(file[i])
          // }
        } else {
        }
      }

      // 上传文件
      this.submitAddFile()
    },
    async submitAddFile() {
      if (0 == this.addArr.length) {
        this.$message({
          type: 'info',
          message: '请选择要上传的文件',
        })
        return
      }

      var formData = new FormData()
      // 就是 form 表单的 js表示方式，key 就是 input 的 name 值
      for (var i = 0; i < this.addArr.length; i++) {
        formData.append('singlefile', this.addArr[i])
      }
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          // Authorization: this.token,
        },
      }

      const { data } = await this.$http.post('/upload', formData, config)
      if (data.code === 200) {
        console.log(data.data)
        // 发送消息给对方
        this.sendMsgFun(null, 1, data.data)
      }
    },

    // 回到聊天选择界面
    backToSelectChat() {
      this.$emit('back-select-chat', { index: 1 })
    },

    // 窗口滚动 滚动耗时 second 毫秒
    scrollChatList(second) {
      // 这个方法刷新应该有延迟，所以用 settimeout 延迟执行下 滚动任务

      this.$nextTick(() => {
        this.bscroll.refresh()
        this.bscroll.scrollTo(0, this.bscroll.maxScrollY, second)
      })
    },

    // 预览图片
    previewImgFun(url) {
      this.previewImgUrl = this.$commonInfo.baseUrl + url
      this.showPreviewImg = true
    },
  },
}
</script>

<style scoped>
.chat {
  width: 100vw;
  height: 100vh;
  position: relative;
}
.chat-title {
  width: 100vw;
  position: absolute;
  left: 0;
  top: 0;
  z-index: 99;

  display: flex;
  justify-content: space-between;
  padding: 0 1rem;
  background-color: #ffffff;
  box-shadow: -2px 0px 10px #cccccc;
  line-height: 4rem;
  font-weight: 600;
}

.wrapper {
  background-color: #ffffff;
  height: calc(100vh - 3rem);
  overflow: hidden;
}

.chat-list {
  padding: 3rem 1rem;
}

.chat-item {
  display: flex;
  padding: 1rem 0;
  align-items: center;
  justify-content: flex-start;
  font-size: 1rem;
}

.chat-item.self {
  justify-content: flex-end;
}

.chat-item .item-content {
  min-width: 6.25rem;
  max-width: 12.5rem;
  padding: 0.6rem 1rem;
  margin: 0 0.625rem;
  border-radius: 10px;
  background-color: #dadada;
  position: relative;
  word-wrap: break-word;
}

.chat-item .item-content i {
  margin-right: 0.625rem;
}

.chat-item.self .item-content {
  background-color: skyblue;
  color: #ffffff;
  position: relative;
}

.chat-item .item-content .sanjiao {
  position: absolute;
  top: 60%;
  transform: translateY(-50%);
  left: -0.9375rem;
  width: 0;
  height: 0;
  border-width: 0.625rem;
  border-style: solid;
  border-color: transparent #dadada transparent transparent;
}

.chat-item.self .item-content .sanjiao {
  position: absolute;
  transform: translateY(-50%);
  left: unset;
  right: -0.9375rem;
  border-color: transparent transparent transparent skyblue;
}

.chat-item img {
  width: 3rem;
  height: 3rem;
  border-radius: 50%;
  border: 2px solid #ffffff;
  box-shadow: 3px 3px 6px #666666;
}
.chat-item.self img {
  width: 3rem;
  height: 3rem;
  border-radius: 50%;
}

.chat-item .time-content {
  position: absolute;
  bottom: -0.9375rem;
  left: 0;
  font-size: 10px;
  /* text-align: center; */
  color: #999999;
}

.input-com {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 3rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #ffffff;
  box-shadow: -2px 0px 10px #cccccc;
}
.input-com input {
  flex: 4;
  height: 3rem;
  border-radius: 5px;
  border: none;
  outline: none;
  background-color: #ffffff;
  padding-left: 10px;
  font-size: 1rem;
}

.input-com input::placeholder{
  color: #cccccc;
}


.input-com > label {
  flex: 1;
  background-color: #ffffff;
  text-align: center;
  font-size: 2rem;
  color: #007acc;
}
.input-com > input[type='file'] {
  /* position: absolute;
  left: 0;
  top: 0;
  z-index: -1; */
  display: none;
}
</style>
